package com.hontech.bvapp2.device.cp

import com.hontech.bvapp2.device.Address
import com.hontech.bvapp2.device.DeviceConn
import com.hontech.bvapp2.device.Frame
import com.hontech.bvapp2.utils.hex16
import com.hontech.bvapp2.utils.isBitSet
import com.hontech.bvapp2.utils.postEvent
import serial.codec.Uint16
import serial.codec.u8

private const val DROP_CUP = 4
private const val LED = 5
private const val FILM_RESTART = 6
private const val ROBOT_RESET = 7
private const val CUT_FILM = 8
private const val FILM = 9

object Drop {

    suspend fun film() {
        DeviceConn.req(Address.DROP, FILM).parse()
    }

    /**
     * 切膜
     * ctrl: 0: 向上, 1: 向下
     */
    suspend fun cutFilm(ctrl: Int) {
        DeviceConn.req(Address.DROP, CUT_FILM, ctrl.u8()).parse()
    }

    suspend fun filmRestart() {
        DeviceConn.req(Address.DROP, FILM_RESTART).parse()
    }

    suspend fun robotRestart() {
        DeviceConn.req(Address.DROP, ROBOT_RESET).parse()
    }

    /**
     * 照明LED/风扇
     * id: 1: LED, 2: 风扇
     * ctrl: 0 打开, 1: 关闭
     */
    suspend fun lightLed(id: Int, ctrl: Int) {
        DeviceConn.simpleReq(Address.DROP, LED, id.u8(), ctrl.u8()).parse()
    }

    /**
     * 落杯
     * id: 1~3
     */
    suspend fun dropCup(id: Int) {
        DeviceConn.req(Address.DROP, DROP_CUP, id.u8()).parse()
    }

    fun onStatus(frame: Frame) {
        val version = Uint16()
        val sensor = Uint16()
        val analog = Uint16()
        frame.parse(version, sensor, analog)
        val s = Status(version.value, sensor.value, analog.value)
        postEvent(s)
        this.status = s
    }

    var status: Status? = null
        private set

    class Status(
        val version: Int,
        val sensor: Int,
        val analog: Int
    ) {

        fun version() = version.hex16()

        fun isDropSw1() = sensor.isBitSet(0)
        fun isDropSw2() = sensor.isBitSet(1)
        fun isDripSw3() = sensor.isBitSet(2)
        fun isFilmSw() = sensor.isBitSet(3)
        fun isFilmCupChecked() = sensor.isBitSet(4)
        fun isCutTop() = sensor.isBitSet(5)
        fun isCutBottom() = sensor.isBitSet(6)
        fun isCutChecked() = sensor.isBitSet(7)
        fun isDropChecked1() = sensor.isBitSet(8)
        fun isDropChecked2() = sensor.isBitSet(9)
        fun isDropChecked3() = sensor.isBitSet(10)
        fun isLeak() = sensor.isBitSet(11)
        fun isWaste() = sensor.isBitSet(12)
        fun isCupChecked() = sensor.isBitSet(13)
    }
}

